package crud.server.util;

import java.awt.Color;
import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.lowagie.text.Cell;
import com.lowagie.text.Document;
import com.lowagie.text.Font;
import com.lowagie.text.PageSize;
import com.lowagie.text.Paragraph;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.pdf.PdfPCell;
import com.lowagie.text.pdf.PdfPTable;
import com.lowagie.text.pdf.PdfWriter;
import common.utils.StringUtil;

import crud.client.constant.CstExport;

public class ExportServlet extends HttpServlet
{

	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		try
		{
			String fileType = request.getParameter("type");
			String separator = request.getParameter("separator");
			String donnee = request.getParameter("donnee");
			donnee = StringUtil.replace(donnee, CstExport.RETOUR_LIGNE, "\n");

			String fileName = request.getParameter("fileName");
			String contentType = "";

			String contentDisposition = "attachment;filename=" + StringUtil.replace(StringUtil.replace(fileName, " ", "_"), "\"", "");
			ServletOutputStream output = response.getOutputStream();

			// Export Excel
			if (CstExport.EXCEL.equals(fileType))
			{
				contentDisposition += ".csv";
				contentType = "text/csv";
				output.write(donnee.getBytes("UTF-8"));
			}
			// Export PDF
			else if (CstExport.PDF.equals(fileType))
			{
				contentDisposition += ".pdf";
				contentType = "application/pdf";

				// La fonte d'impression
				Font font = new Font(BaseFont.createFont("C:\\WINDOWS\\FONTS\\ARIAL.TTF", BaseFont.IDENTITY_H, BaseFont.EMBEDDED), 9, Font.NORMAL);

				// Le document Pdf (Paysage)
				Document document = new Document(PageSize.A4.rotate());
				document.setMargins(10, 10, 10, 10);
				PdfWriter.getInstance(document, output);
				document.open();

				// Parsing de la liste des données
				List<String> ligneList = Arrays.asList(donnee.split("[\n]"));
				PdfPTable pdfTable = new PdfPTable(ligneList.get(0).split("[" + separator + "]").length);

				for (int cpLigne = 0; cpLigne <= ligneList.size() - 1; cpLigne++)
				{
					String ligne = ligneList.get(cpLigne);
					List<String> colonneList = Arrays.asList(ligne.split("[" + separator + "]"));

					for (int i = 0; i <= colonneList.size() - 1; i++)
					{
						String valeur = colonneList.get(i);
						PdfPCell cell = new PdfPCell();
						Paragraph paragraph = new Paragraph(valeur, font);
						cell.addElement(paragraph);

						if (cpLigne == 0)
						{
							cell.setBackgroundColor(Color.LIGHT_GRAY);
							cell.setBorder(Cell.LEFT | Cell.RIGHT | Cell.BOTTOM | Cell.TOP);
							paragraph.setAlignment(Paragraph.ALIGN_CENTER);
						} else
						{
							// Alignement das la cellule
							try
							{
								@SuppressWarnings("unused")
								Date date = StringUtil.toDate(valeur);
								paragraph.setAlignment(Paragraph.ALIGN_CENTER);
							} catch (Exception e)
							{
								try
								{
									@SuppressWarnings("unused")
									Integer integer = Integer.valueOf(valeur);
									paragraph.setAlignment(Paragraph.ALIGN_RIGHT);
								} catch (Exception ex)
								{
									paragraph.setAlignment(Paragraph.ALIGN_LEFT);
								}
							}
							
							
							if (cpLigne == ligneList.size() - 1)
							{
								cell.setBorder(Cell.LEFT | Cell.RIGHT | Cell.BOTTOM);
							} else
							{
								cell.setBorder(Cell.LEFT | Cell.RIGHT);
							}
						}
						pdfTable.addCell(cell);
					}
				}

				document.add(pdfTable);
				document.close();
			}

			response.setContentType(contentType);
			response.setHeader("Content-Disposition", contentDisposition);
			// response.setHeader("Content-Type", contentType);
			// response.setHeader("Content-transfer-encoding", "UTF-8");

			// copy binary contect to output stream
			output.flush();
			output.close();
		} catch (Exception e)
		{
			throw new RuntimeException(e);
		}

	}

	@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		doGet(request, response);
	}
}
